/*============================================================================
 PROJECT: TalkWrench
 FILE:    PhotoPresentationView.m
 AUTHOR:  MACBOOK PRO
 DATE:    2/23/13
 =============================================================================*/

/*============================================================================
 IMPORT
 =============================================================================*/
#import "PhotoPresentationView.h"
#import "PhotoPresentationCell.h"

/*============================================================================
 PRIVATE MACRO
 =============================================================================*/
/*============================================================================
 PRIVATE INTERFACE
 =============================================================================*/


@implementation PhotoPresentationView
@synthesize delegate;
@synthesize holderViewController;

static PhotoPresentationView *sharedObj;

+ (PhotoPresentationView *)sharedPhotoPresentationView {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(!sharedObj) {
            sharedObj = [[IBHelper sharedUIHelper] loadViewNib:@"PhotoPresentationView"];
        }
    });
    return sharedObj;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    _photoTableView.delegate = self;
    _photoTableView.dataSource = self;
    _photoTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    _photoTableView.transform = CGAffineTransformMakeRotation(-M_PI_2);
    CGRect rect = _photoTableView.frame;
    
    _photoTableView.frame = CGRectMake(0, 0  , rect.size.height, rect.size.width);
    
    self.frame = kScreenFrame;
    
}

#pragma mark Properties
- (BOOL)canMoveNext {
    NSInteger maxCount = (ArrCount(self.photos) > 0 ? ArrCount(self.photos) : ArrCount(self.photoURLs));
    return _currentPhotoIndex < maxCount - 1 ? YES : NO;
}

- (BOOL)canMovePrevious {
    return _currentPhotoIndex > 0 ? YES : NO;
}

- (void)setEditButtonHidden:(BOOL)hidden {
    /* get toolbar from parent view */
    UIToolbar   *toolBar = nil;
    for (UIView *view in self.subviews) {
        if(IsKindOfClass(view, [UIToolbar class])) {
            toolBar = (UIToolbar *)view;
            break;
        }
    }
    
    /* get delete button and hide it */
    UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash
                                                                            target:self
                                                                            action:@selector(didTouchedDeleteButton:)];
    UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                                                            target:self
                                                                            action:@selector(didTouchedCancelButton:)];
    UIBarButtonItem *button3 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                            target:nil
                                                                            action:nil];
    if (hidden) {
        [toolBar setItems:@[button2]];
    } else {
        [toolBar setItems:@[button2, button3, button1]];
    }
}

#pragma mark public functions

- (void)showOnViewController:(UIViewController *)controller {
    
    /* don't show if visibling */
    if(visibling) {
        return;
    }
    visibling = YES;
    
    /* keep present view controller */
    self.holderViewController = controller;
    
    
    /* show if hidden view */
    if(!self.superview) {
        
        /* get top window */
        NSArray *windows = [UIApplication sharedApplication].windows;
        UIWindow    *topWindow = ArrLastObj(windows);
        [topWindow addSubview:self];
        _backgroundView.alpha = 0;
        
        /* scale view to 0.1 for preparing to zoom again */
        self.transform = CGAffineTransformMakeScale(0.1, 0.1);
        [UIView animateWithDuration:0.35f
                         animations:^{
                             self.transform = CGAffineTransformMakeScale(1, 1);
                         }
                         completion:^(BOOL finished) {
                             _backgroundView.alpha = 1;
                             
                             // load photos
                             [_photoTableView reloadData];
                             
                             // scroll to current selected index
                             [self showImageAtIndex:_currentPhotoIndex];
                         }];
    }
    
}

- (void)hide {
    /* don't hide if hidden */
    if(!visibling) {
        return;
    }
    visibling = NO;
    
    /* hide it */
    if (self.superview) {
        _backgroundView.alpha = 0;
        
        /* scale view to 0.1 for preparing to zoom again */
        [UIView animateWithDuration:0.35f
                         animations:^{
                             self.transform = CGAffineTransformMakeScale(0.1, 0.1);
                         }
                         completion:^(BOOL finished) {
                             [self removeFromSuperview];
                         }];
    }
}

- (IBAction)didTouchedCancelButton:(id)sender {
    [self hide];
}

- (IBAction)didTouchedDeleteButton:(id)sender {
    UIAlertView *confirmView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Confirmation", @"Navigation Bar Title")
                                                          message:NSLocalizedString(@"Are you sure to remove this picture ?", @"UIButton")
                                                         delegate:self
                                                cancelButtonTitle:NSLocalizedString(@"Cancel", @"UIButton")
                                                otherButtonTitles:@"Yes", nil];
    [confirmView show];
}

- (IBAction)onTouchedPreviousOrNextButton:(id)sender {
    _currentPhotoIndex = (_currentPhotoIndex > 0 ? _currentPhotoIndex - 1 : _currentPhotoIndex);
    [self showImageAtIndex:_currentPhotoIndex];
}

- (IBAction)didTouchedOnNextButton:(id)sender {
    NSInteger maxCount = (ArrCount(self.photos) > 0 ? ArrCount(self.photos) : ArrCount(self.photoURLs));
    _currentPhotoIndex = (_currentPhotoIndex < (maxCount - 1) ? _currentPhotoIndex + 1 : _currentPhotoIndex);
    [self showImageAtIndex:_currentPhotoIndex];
}


#pragma mark Private functions

- (void)showImageAtIndex:(NSInteger)index {
    
    // hide/show Next/Previous Button
    [self showHidePreviousAndNextControl];
    
    NSInteger maxCount = (ArrCount(self.photos) > 0 ? ArrCount(self.photos) : ArrCount(self.photoURLs));
    if (maxCount > 0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        [_photoTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];
        
        // notify did show image
        if (delegate && [delegate respondsToSelector:@selector(photoPresentationView:didShowPhotoAtIndex:)]) {
            [delegate photoPresentationView:self didShowPhotoAtIndex:index];
        }
    }
}

- (void)showHidePreviousAndNextControl {
    _previousButton.hidden = !self.canMovePrevious;
    _nextButton.hidden = !self.canMoveNext;
}

#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { // OK
        if (self.photos.count > 0) {
            [self.photos removeObjectAtIndex:_currentPhotoIndex];
            // reload photo list
            [_photoTableView beginUpdates];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentPhotoIndex inSection:0];
            [_photoTableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationLeft];
            [_photoTableView endUpdates];
            
            if (delegate && [delegate respondsToSelector:@selector(photoPresentationView:didDeletePhotoAtIndex:)]) {
                [delegate photoPresentationView:self didDeletePhotoAtIndex:_currentPhotoIndex];
            }
            
            _currentPhotoIndex = _currentPhotoIndex > self.photos.count -1 ? (_currentPhotoIndex > 0 ? self.photos.count - 1: 0) : _currentPhotoIndex;
        }
        
    }
}

#pragma mark UITalbeViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 320;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (self.photos.count > 0 ? self.photos.count : self.photoURLs.count);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"PhotoPresentationCell";
    PhotoPresentationCell *cell = [self.photoTableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[IBHelper sharedUIHelper] loadViewNib:identifier];
    }
    
    if(ArrCount(self.photos)) {
        [cell updateWithImage:(self.photos)[indexPath.row]];
    } else {
        /* get image URL */
        NSString *imageURL = ArrObj4Idx(self.photoURLs, indexPath.row);
        
        /* update image URL */
        [cell updateWithURL:imageURL];
    }
    return cell;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // get current index of presented image 
    NSIndexPath *visibleCellIndexPath = (_photoTableView.indexPathsForVisibleRows)[0];
    DLog(@"index image: %d", visibleCellIndexPath.row);
    _currentPhotoIndex = visibleCellIndexPath.row;
    DLog(@"current index: %d",_currentPhotoIndex);
    [self showHidePreviousAndNextControl];
}

@end
